﻿/*
* @Author: z.p
* @Project: Zdotp
* @Date: 2025年01月01日
* @Description: 多网关demo客户端展示
*/

using Pb;
using Zdotp.Actor;
using Zdotp.Logs;
using Zdotp.Net.Kcp.App;
using Zdotp.Net.NetMessageHandler;
using Zdotp.Pb;

namespace MutliGateClient;

internal class Program
{
    private static Task _checker;
    
    private static ZLogger _logger;
    
    public static async Task Main(string[] args)
    {
        _logger = LogHelper.CreateLogger("client");
        KcpNetHandlerManager.LoadAssemblies([typeof(ActorBase).Assembly]);
        
        var client = new ClientApp
        {
            OnConnected = _ => _logger.Info("连接服务器成功"),
            OnDisconnected = _ => _logger.Info("断开服务器连接"),
            OnReceive = (_, packet) =>
            {
                var protocolId = BitConverter.ToUInt32(packet);
                var dataPacket = packet.Skip(4).ToArray().Deserialize<DataPacket>();
                _logger.Info($"收到服务器消息, protocolId : {protocolId}, data : {dataPacket?.Content}");
            }
        };

        _logger.Info($"请输入连入哪个网关: 1 or 2");
        
        var port = 7890;
        var line = Console.ReadLine();
        if (line == "2") port = 7891;
        
        client.Start("127.0.0.1", port);
        
        // 每0.1s尝试连接一次, 一共尝试5s, 直到连接成功, task返回
        // 可以写重连逻辑
        _checker = client.ClientConnectServer(0.1f, 5);
        await _checker;

        var packet = new DataPacket();
        
        while (true)
        {
            var readLine = Console.ReadLine();
            if (_checker is { IsCompleted: true })
            {
                packet.Content = readLine;
                client.SendMsgToServer(1, packet.Serialize());
            }
            if (readLine == "exit") break;
        }
        client.Close();
        Console.ReadLine();
    }
}